/**
 * 默认配置
 */
var default_config = {
	upload_url:contextPath + '/attachment/upload.shtml?moudle=atta',
	download_url:contextPath + '/attachment/down.shtml',
	delete_url:contextPath + '/attachment/delete.shtml',
	script_path:contextPath + '/resources/script/swfupload/',
	preview_url:contextPath + '/attachment/display.shtml'
};

var StringBuffer = function(){
	this._strs = new Array();
};
StringBuffer.prototype.append = function(str){
	this._strs.push(str);
	return this;
};
StringBuffer.prototype.toString = function(){
	return this._strs.join("");
};


/**
 * 上传文件错误时触发
 * @param file
 * @param errorCode
 * @param message
 */
function fileQueueError(file, errorCode, message) {

	try {
		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			alert("文件大小为0");
			break;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			alert("文件大小超过限制");
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			alert("文件扩展名不符上传规定");
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			alert("文件上传数超过限制");
			break;
		default:
			alert('文件上传错误');
			break;
		}
		
	} catch (ex) {
		this.debug(ex);
	}
}

/**
 * 上传文件弹出窗口，窗口关闭触发
 * @param numFilesSelected
 * @param numFilesQueued
 */
function fileDialogComplete(numFilesSelected, numFilesQueued) {

	try {
		if (numFilesQueued > 0) {

			document.getElementById(this.customSettings.cancel_upload).disabled = "";
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}


/**
 * 当文件选择对话框关闭消失时，如果选择的文件成功加入上传队列，
 * 那么针对每个成功加入的文件都会触发一次该事件（N个文件成功加入队列，就触发N次此事件）。
 * @param {} file
 * id : string,			    // SWFUpload控制的文件的id,通过指定该id可启动此文件的上传、退出上传等
 * index : number,			// 文件在选定文件队列（包括出错、退出、排队的文件）中的索引，getFile可使用此索引
 * name : string,			// 文件名，不包括文件的路径。
 * size : number,			// 文件字节数
 * type : string,			// 客户端操作系统设置的文件类型
 * creationdate : Date,		// 文件的创建时间
 * modificationdate : Date,	// 文件的最后修改时间
 * filestatus : number		// 文件的当前状态，对应的状态代码可查看SWFUpload.FILE_STATUS }
 */
function fileQueued(file){

	try {
		addFile({
			type:'add',
			fileId:file.id,
			fileName:file.name,
			fileSize:formatFileSize(file.size),
			table:this.customSettings.upload_table
		});
	} catch (ex) {
		this.debug(ex);
	}
	
}

/**
 * 文件上传中(进度条功能)
 * @param file
 * @param bytesLoaded
 */
function uploadProgress(file, bytesLoaded) {
	try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);
		$("#"+file.id).find(".progress_bar").css("width",percent+"%");
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {

	try {
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			alert("文件上传出错,请检查文件上传路径");
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			alert("取消上传!");
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			alert("停止上传!");
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			alert("文件大小超过限制");
			break;
		default:
			alert("文件上传出错");
			break;
		}
	} catch (ex3) {
		this.debug(ex3);
	}

}

/**
 * 文件上传成功
 * @param file
 * @param serverData 服务端返回的数据
 */
function uploadSuccess(file, serverData) {
	
	try {
		var data = $.parseJSON(serverData);
		//console.log(data);
		file.attId = data.attId;
		file.filePath = data.filePath;

		var row = document.getElementById(file.id);
		var _fileState = new StringBuffer();
		var fileType = this.customSettings.fileType;
		_fileState.append("<input type='hidden' id='attId' name='")
					.append(this.customSettings.atta_name)
					.append("' value='").append(file.attId).append("'/>");
		_fileState.append("<input type='hidden' id='filePath' name='filePath' value='").append(file.filePath).append("'/>");
		_fileState.append("<input type='hidden' id='fileType' name='fileType' value='").append(fileType).append("'/>");
		_fileState.append("<input type='hidden' id='fileSize' name='fileSize' value='").append(formatFileSize(file.size)).append("'/>");
		_fileState.append("<font color='green'>文件上传完成</font>");

		$(row.cells[3]).html(_fileState.toString());
		//添加下载按钮
		var _downFile = new StringBuffer();
		_downFile.append('<a target=_blank href="').append(this.customSettings.download_url)
				 .append('?attId=').append(file.attId).append('">');
		_downFile.append('<img src="').append(default_config.script_path);
		_downFile.append('images/icon/down.png" width="16" height="16" style="vertical-align:middle;" alt="下载文件"/></a>');
		$(row.cells[4]).append(_downFile.toString());
		// 添加预览文件按钮(如果是可预览类型的，添加可预览)
		var _priviewFile = new StringBuffer();
		if (isVaildFile(file.filePath, "IMG")) {
			//跳转到页面读取图片
			_priviewFile.append('&nbsp;<a target=_blank href="').append(this.customSettings.preview_url)
			 			.append('?type=img&attId=').append(file.attId).append('">');
			_priviewFile.append('<img src="').append(default_config.script_path);
			_priviewFile.append('images/icon/preview.png" width="16" height="16" style="vertical-align:middle;" alt="预览文件"/></a>');
		} else if (isVaildFile(file.filePath, "PDF")) {
			// 跳转到PDF展示页面
			_priviewFile.append('&nbsp;<a target=_blank href="').append(this.customSettings.preview_url)
			 			.append('?type=pdf&attId=').append(file.attId).append('">');
			_priviewFile.append('<img src="').append(default_config.script_path);
			_priviewFile.append('images/icon/preview.png" width="16" height="16" style="vertical-align:middle;" alt="预览文件"/></a>');
		}
		$(row.cells[4]).append(_priviewFile.toString());
		
		// 给文件名添加上下载链接
		var _newFileName = new StringBuffer();
		_newFileName.append('<a target=_blank href="')
		.append(this.customSettings.download_url)
		.append('?attId=').append(file.attId).append('">')
		.append(displayFileName(file.name)).append('</a>');
		/*if (isImage(file.name)) {
			//console.log(file);
			_newFileName
					.append('<a href="javascript:showImage(\'' + file.filePath
							+ '\',\'' + file.attId + '\',\'' + file.name
							+ '\');">' + displayFileName(file.name) + '<a>');
		} else {
			_newFileName.append('<a target=_blank href="')
						.append(this.customSettings.download_url)
						.append('?attId=').append(file.attId).append('">')
						.append(displayFileName(file.name)).append('</a>');
		}*/
		
		$(row.cells[1]).html(_newFileName.toString());			
		
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	
	try {
		//上传文件数+1
		$("#fileNum").val(parseInt($("#fileNum").val())+1);
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		} else {
			//alert('所有文件上传完毕!');
		}
	} catch (ex) {
		this.debug(ex);
	}
}

/**
 * 根据文件名截取文件后缀
 * @param fileName
 * @returns
 */
function getFileSuffix(fileName){ 
	if(typeof fileName === 'undefined'){
		return '';
	}else{
		var len = fileName.lastIndexOf('.'); 
		return fileName.substr(len+1,fileName.length);
	}
	 
}  

/**
 * 文件名太长...显示
 * @param fileName
 * @returns
 */
function displayFileName(fileName){	
	if(typeof fileName === 'undefined'){
		return '';
	}else{
		if(fileName.length > 20){
			var _name = new StringBuffer();
			_name.append("<span style='cursor:pointer' title='").append(fileName).append("'>");
			_name.append(fileName.substring(0,20)).append("……").append("</span>");
			return _name.toString();
		}
		return fileName;
	}
}

/**
 * 格式化文件大小
 * @param {Object} fileSize
 */
function formatFileSize(fileSize) {
	var size = fileSize;
	var unit = "B";
	if (size > (1024 * 1024 * 1024)) {
		unit = "GB";
		size /= (1024 * 1024 * 1024);
	} else if (size > (1024 * 1021)) {
		unit = "MB";
		size /= (1024 * 1024);
	} else if (size > 1024) {
		unit = "KB";
		size /= 1024;
	} 
	return size.toFixed(2)+unit;
}


function showImage(filedomain, filePath, fileName){
    fileName = fileName.toUpperCase();
    if(fileName.indexOf(".PNG")!=-1 || fileName.indexOf(".JPG")!=-1 || fileName.indexOf(".JPEG")!=-1
        || fileName.indexOf(".GIF")!=-1 || fileName.indexOf(".BMP")!=-1) {
    	//console.log(filedomain);
        showImageViewer(filePath);
    } else {
    	//var url = '<%=path%>'+'/'+fileSrc;
        //location.href = url;
    }
}


/**
 * 往表格添加文件信息file, upload_table, type
 * @param result
 * var result = {
 * 		fileId:'',
 * 		fileName:'',
 * 		filePath:'',
 * 		fileSize:'',
 * 		tableName:'',
 * 		type:'',//type add、edit、detail
 * 		delFileMethod:''
 * }
 */
function addFile(result){
	var imgStr = "bmp,doc,docx,txt,xls,tif,rtf,xml,ppt,ppx,png,pdf,jpg,gif,pdm,sql,apk";
	var suffix = getFileSuffix(result.fileName);
	if(imgStr.indexOf(suffix)<0){
		suffix = "epub";
	} 
	var row = new StringBuffer();
	row.append('<tr id="').append(result.fileId).append('" type="').append(result.type).append('" path="').append(result.filePath+'">');
	row.append('<td align="center" width="20px">');
	row.append('<img src="').append(default_config.script_path).append('images/icon/icon_').append(suffix).append('.gif" width="16" height="16" />');
	row.append('</td>');
	row.append('<td align="left">');
	//console.log('-------------------------------->>>result:  ');
	//console.log(result);
//	row.append('<a target=_blank href="').append(default_config.download_url).append('&attId=').append(result.fileId).append('">')
//	.append(displayFileName(result.fileName)).append('</a></td>');
	
	if(result.download_url){
//		if ("bmp,png,pdf,jpg,gif".indexOf(suffix) > -1) {
//			console.log(suffix + '====');
//			row.append('<a href="javascript:showImage(\''+result.filePath +'\',\''+result.fileId +'\',\''+result.fileName+'\');">'+displayFileName(result.fileName)+'<a>');
//		} else {
			row.append('<a target=_blank href="')
					.append(default_config.download_url)
					.append('?attId=')
					.append(result.fileId).append('">')
					.append(displayFileName(result.fileName))
					.append('</a>');
//		}
	} else {
		row.append(displayFileName(result.fileName));
	}
	//console.log('<<<<<--------------------------------');
	row.append('</td>');
	
	
	row.append('<td width="50" align="center">').append(result.fileSize).append('</td>');
	row.append('<td width="100" align="center">');
	if(result.type=='add'){
		row.append('<div class="bar"><div class="progress_bar"></div></div>');//新增添加进度条
	}
	row.append('</td>');
	row.append('<td width="100" align="center">');
	if(result.type != 'detail'){//文件详情无下载图片		 
		row.append('<img src="').append(default_config.script_path).append('images/icon/folder_del.gif" width="16" height="16" ')
		   .append('style="cursor:pointer;vertical-align:middle;"')
		   .append(' onclick="deleteFile(').append(result.fileId).append(');" alt="删除文件"/>&nbsp;');

	}
	//console.log('--------->>>' + result.type);
	if('add' != result.type){		 
		row.append('<a target=_blank href="').append(result.download_url).append('?attId=').append(result.fileId).append('">')
		   .append('<img src="').append(default_config.script_path).append('images/icon/down.png" width="16" height="16"')
		   .append(' style="vertical-align:middle;" alt="下载文件"/></a>');
		
		if (isVaildFile(result.fileName, "IMG")) {
			//跳转到页面读取图片
			row.append('&nbsp;<a target=_blank href="').append(result.preview_url).append('?type=img&attId=').append(result.fileId).append('">')
			   .append('<img src="').append(default_config.script_path).append('images/icon/preview.png" width="16" height="16"')
			   .append(' style="vertical-align:middle;" alt="预览文件"/></a>');
		} else if (isVaildFile(result.fileName, "PDF")) {
			// 跳转到PDF展示页面
			row.append('&nbsp;<a target=_blank href="').append(result.preview_url).append('?type=pdf&attId=').append(result.fileId).append('">')
			   .append('<img src="').append(default_config.script_path).append('images/icon/preview.png" width="16" height="16"')
			   .append(' style="vertical-align:middle;" alt="预览文件"/></a>');
		}
	}
	row.append('</td>');  
	$("#"+result.table).append(row.toString());
	
}


/**
 * 删除全部上传文件
 * @param upload_table
 */
function cancelUpload(upload_table){
	
	$('#'+upload_table+' tr').each(function(index, element) {
		if(element.id){
			deleteFile(element.id);
		}
    });
}
/**
 * 删除文件
 * @param id 文件ID
 */
function deleteFile(id){
	
	var x = id;
	if(typeof id  == 'object'){
		id = id.id;
	}
	
	var type = $("#"+id).attr("type");
	
	if(type=='add'){
		var filePath = $("#"+id).find("#filePath").val();	
		$.ajax({
			type: "POST",
		   	url: default_config.delete_url,
		   	data: {'filePath':filePath},
		   	success: function(msg){
				//if(msg=='-1'){
		   		if(!msg.success){
					alert('删除附件失败');
				}else{
					$("#"+id).remove();
				}
		   	}
		});
	} else if(type=='edit'){
		
		var filePath = $("#"+id).attr("path");
		if(filePath=='undefined'){
			$("#"+id).remove();
		} else{
			//delFile(id,filePath);//自定义删除附件function
			$.ajax({
				type: "POST",
			   	url: default_config.delete_url,
			   	data: {'filePath':filePath,'attId':x},
			   	success: function(msg){
					//if(msg=='-1'){
			   		if(!msg.success){
						alert('删除附件失败');
					}else{
						$("#"+id).remove();
					}
			   	}
			});	
		}
	}
	
	var stats =swfUpload.getStats();
	stats.successful_uploads = 0;
	swfUpload.setStats(stats);
	//文件数-1
	$("#fileNum").val(parseInt($("#fileNum").val())-1);
	
}


$(function(){
	$(".can_btn").hover(
	  	function () {
			$(".can_btn").css("background-position","left -21px");
	  	},
	  	function () {
	    	$(".can_btn").css("background-position","left top");
	  	}
	);	
});
/**
 * 初始化文件
 * @param _config
 *	var _config = {
 * 		positionId:'附件列表DIV的id值',
 * 		upload_table:'logo',//表格ID
 *		cancel_button:'cancel_button1'//取消全部按钮
 * 	    fileSize:'fileSize1',//自定义文件属性
 *	    filePath:'filePath1',//自定义文件属性
 *	    fileName:'fileName1',//自定义文件属性
 *      type:'',//add edit detail
 *      initType:'',//ajax、hidden()
 *      ajaxUrl:'',
 *      ajaxData:'',
 *      hiddenId:'',
 *      upload_url:'',//文件上传路径
 *      file_upload_limit:''
 *      file_size_limit:'',//默认1024M
 *      file_types:'',//默认*.*
 *	}
 */
function fileUpload(_config){
	 

	var _type = _config.type; 
	var _cancel_button = _config.cancel_button || 'cancel_button';
	var _upload_table = _config.upload_table || 'upload_table';
	var _atta_name = _config.atta_name || 'attId';

	//1、init  div
	var _content = new StringBuffer();
	if(_config.type != 'detail'){
		_content.append('<div id="upload_file"></div>&nbsp;&nbsp;&nbsp;&nbsp;');
		if(_config.noDiplay){
		_content.append('<input id="').append(_cancel_button).append('"  style="display:none;" type="button" value="取消所有上传"');
		_content.append('onclick="cancelUpload(\'').append(_upload_table).append('\');" class="can_btn" disabled="disabled"/>');
 		}else{
 		_content.append('<input id="').append(_cancel_button).append('" type="button" value="取消所有上传"');
		_content.append('onclick="cancelUpload(\'').append(_upload_table).append('\');" class="can_btn" disabled="disabled"/>');
 		}
			

		_content.append('<input type="hidden" id="fileNum" name="fileNum" value="0"/>');
	}
	if(_config.noDiplay){
		_content.append('<table id="').append(_upload_table).append('" style="width:98% !important;display:none;" class="upload_table">');
	}else{
		_content.append('<table id="').append(_upload_table).append('" style="width: 98% !important;" class="upload_table">');
	}

	_content.append('<tr><th colspan="2" align="left" style="padding-left:20px;">文件名称</th>')
			.append('<th style="width:80px !important">大小</th><th style="width:100px !important">状态</th>');
	_content.append('<th style="width:100px !important">操作</th></tr></table>');
	$("#"+_config.positionId).html(_content.toString());
	
	//2、init data
	if(_config.initType=='ajax'){
		//AJAX从Action获取Json Data并加载
		$.ajax({
			type: "POST",
			async:false,
		   	url: _config.ajaxUrl,
		   	data: _config.ajaxData||{},
		   	dataType:'json',
		   	success: function(result){
		   		if(result!=null){
		   			$("#fileNum").val(result.length);
		   			if (0 == result.length && _config.type == 'detail') {
		   				//console.log('detail');
		   				var _no_data = '<tr><td colspan="5">未上传相关文件</td></tr>';
			   			$('#' + _upload_table).append(_no_data);
		   			}
					$(result).each(function(e){
						addFile({
							type:_type,
							fileId:this.attId,
							fileName:this.fileName,
							fileSize:this.fileSize,
							filePath:this.filePath,
							table:_upload_table,
							download_url : _config.download_url || default_config.download_url,
							preview_url : _config.preview_url || default_config.preview_url
						});
					});
					var cheight = $("#contentborder").height();
					$('#' + _upload_table).height();
					//console.log(cheight);
					//console.log($('#' + _upload_table).outerHeight(true));					
					if(cheight != null) {
						//alert('contentborder.height00--'+cheight);
						//var layout = $('#centerContent').layout();
						//var center = layout.layout('panel','center').panel('resize', {height: cheight});
//						//console.log(center);
//						$('#centerContent').layout('panel', 'center');
						//.resize({height:cheight});
						//.panel('resize',{height:cheight});
						//$('#centerContent').layout('resize');
						$("#contentFrame", parent.document).height(cheight);
						////console.log($("#formFrame", parent.document).height());
					}
					
		   		} else {
		   		}
		   	}
		});
	} else if(_config.initType == 'hidden'){
		//从隐藏域获取数据并加载
		var result = $.parseJSON($("#"+_config.hiddenId).val());
		$(result).each(function(e){
			addFile({
				type:_type,
				fileId:this.attId,
				fileName:this.fileName,
				fileSize:this.fileSize,
				filePath:this.filePath,
				table:_upload_table,
				download_url : _config.download_url || default_config.download_url,
				preview_url : _config.preview_url || default_config.preview_url
			});
		});
	}
	
	//3、 init fileupload comp
	if(_type != 'detail'){
		
		var config  = {
			upload_url: _config.upload_url||default_config.upload_url,
			// File Upload Settings
			file_size_limit : _config.file_size_limit||"102400000000 MB",	// 1000MB
			file_types:_config.file_types||"*.doc;*.docx;*.xls;*.xlsx;*.txt;*.jpg;*.gif;*.png;*.rar;*.zip;*.tif;*.pdf;*.apk;*.ppt;*.pptx;*.pdm;*.apk;*.sql;",//文件类型
			//file_types_description : "产品LOGO",
			file_upload_limit:_config.file_upload_limit||50,
			//file_queue_limit:10,
			//file_dialog_start_handler:fileDialog,
			file_queue_error_handler : fileQueueError,//上传文件错误时触发
			file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交
			file_queued_handler : fileQueued,//选择完文件后就触发
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,//上传错误触发
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			// Flash Settings
			flash_url : default_config.script_path+"swfupload.swf",
			button_placeholder_id : "upload_file",
			button_image_url: default_config.script_path+"images/btn4.gif",
			button_text : '<span class="theFont">上传文件</span>',
			button_width: 81,
			button_height: 21,
			button_text_left_padding: 12,
			custom_settings : {
				cancel_upload: _cancel_button,
				upload_table : _upload_table,
				fileType : _config.fileType||'fileType',
				upload_target: 'file_progress',
				download_url : _config.download_url || default_config.download_url,
				atta_name : _atta_name,
				preview_url : _config.preview_url || default_config.preview_url
			}//,debug:true
		};

		swfUpload = new SWFUpload(config);
	}
	
//	console.log('=========================fileUpload===============================');
}


function isImage(fileName) {
	var imgStr = "bmp,png,pdf,jpg,gif";
	var suffix = getFileSuffix(fileName);
	if(imgStr.indexOf(suffix)<0){
		suffix = "epub";
	} 
	if(imgStr.indexOf(suffix)<0){
		return false;
	}
	return true;
}

